gameInfo = {
    roomId: null,
    thisUserId: null,
    thatUserId: null,
    isWhite: true,
}


webSocketUrl="ws://"+location.host+"/game1";
webSocket = new WebSocket(webSocketUrl);





webSocket.onclose = function () {
    console.log('服务器连接已关闭,返回大厅');
    location.replace("/game_hub.html");
};
webSocket.onerror = function () {
    console.log('WebSocket连接异常');
};
webSocket.onopen = function () {
    console.log('开启webSocket连接 ');
};
// 关闭页面时关闭连接 
window.onbeforeunload = function () {
    webSocket.close();
};

//////////////////////////////////////////////////
// 设定界面显示相关操作
//////////////////////////////////////////////////

function setScreenText(me) {
    let screen = document.querySelector('#screen');
    if (me) {
        screen.innerHTML = "轮到你落子了!";
    } else {
        screen.innerHTML = "轮到对方落子了!";
    }
}

//////////////////////////////////////////////////
// 初始化 websocket
//////////////////////////////////////////////////
// TODO

//////////////////////////////////////////////////
// 初始化一局游戏
//////////////////////////////////////////////////
function initGame() {
    // 是我下还是对方下. 根据服务器分配的先后手情况决定
    me = gameInfo.isWhite;
    // 游戏是否结束
    over = false;
    chessBoard = [];
    //初始化chessBord数组(表示棋盘的数组)
    for (let i = 0; i < 15; i++) {
        chessBoard[i] = [];
        for (let j = 0; j < 15; j++) {
            chessBoard[i][j] = 0;
        }
    }
    chess = document.querySelector('#chess');
    context = chess.getContext('2d');
    context.strokeStyle = "#BFBFBF";
    // 背景图片
    logo = new Image();
    logo.src = "../pic/wood.jpg";
    logo.onload = function () {
        context.drawImage(logo, 0, 0, 450, 450);
        initChessBoard();
    }

    // 绘制棋盘网格
    function initChessBoard() {
        for (let i = 0; i < 15; i++) {
            context.moveTo(15 + i * 30, 15);
            context.lineTo(15 + i * 30, 430);
            context.stroke();
            context.moveTo(15, 15 + i * 30);
            context.lineTo(435, 15 + i * 30);
            context.stroke();
        }
    }

    // 绘制一个棋子, me 为 true       
}
chess.onclick = function (e) {
    if (over) {
        return;
    }
    if (!me) {
        return;
    }
    let x = e.offsetX;
    let y = e.offsetY;
    // 注意, 横坐标是列, 纵坐标是行
    let col = Math.floor(x / 30);
    let row = Math.floor(y / 30);
    if (chessBoard[row][col] == 0) {
        // TODO 发送坐标给服务器, 服务器要返回结果
        console.log("this 这里的id 是" + gameInfo.thisUser);
        one = {
            row: row,
            col: col,
            userId: gameInfo.thisUserId,
            message: "putChess"
        };
        console.log("向服务器发送" + one.data);
        webSocket.send(JSON.stringify(one));

        // oneStep(col, row, gameInfo.isWhite);
        // chessBoard[row][col] = 1;
    }
}
function oneStep(i, j, isWhite) {
    context.beginPath();
    context.arc(15 + i * 30, 15 + j * 30, 13, 0, 2 * Math.PI);
    context.closePath();
    var gradient = context.createRadialGradient(15 + i * 30 + 2, 15 + j * 30 - 2, 13, 15 + i * 30 + 2, 15 + j * 30 - 2, 0);
    if (!isWhite) {
        gradient.addColorStop(0, "#0A0A0A");
        gradient.addColorStop(1, "#636766");
    } else {
        gradient.addColorStop(0, "#D1D1D1");
        gradient.addColorStop(1, "#F9F9F9");
    }
    context.fillStyle = gradient;
    context.fill();
}

webSocket.onmessage = function (r) {
    msg = JSON.parse(r.data);
    console.log("收到来自服务器的报文");
    console.log(msg);

    if (msg.code != "SUCCESS") {
        alert("连接游戏失败" + msg.errMsg);
        location.replace("/game_hub.html");
        return;
    }
    if (msg.message == "gameStart") {
        console.log("收到来自服务器的报文");
        console.log(msg);
        gameInfo.roomId = msg.roomId;
        gameInfo.thisUserId = msg.thisUser;
        gameInfo.thatUserId = msg.thatUser;
        gameInfo.isWhite = (msg.isWhite == msg.thisUser);
        initGame();
        console.log("收到来自服务器的报文");
        console.log("是不是白方" + gameInfo.isWhite);
        setScreenText(gameInfo.isWhite);

    }

    if (msg.message == "落子成功") {
        let col = msg.col;
        let row = msg.row;
        console.log("userid/iswhite:" + msg.userId + "/" + gameInfo.isWhite);
        screen =document.querySelector("#screen");
        
        if (msg.userId == gameInfo.thisUserId) {
            oneStep(col, row, gameInfo.isWhite);
        } else {
            oneStep(col, row, !gameInfo.isWhite);
        }

        if (msg.winnerId != 0) {
            if (msg.winnerId == gameInfo.thisUserId) {
                // alert("你赢了!");
                screen.innerHTML="你赢了! ";
                
            } else if (msg.winnerId == gameInfo.thatUserId) {
                // alert("你输了!");
                screen.innerHTML="你输了! ";
            } else if (msg.winnerId == -1) {
                // alert("平局");
                screen.innerHTML="平局! ";

            } else {
                alert("响应错误 赢家id为" + msg.winnerId);
                // location.assign("game_hub.html");

            }
            back = document.createElement('button');
            back.Width="200px";
            back.Height='50px';
            back.innerHTML="返回大厅";
            back.onclick= function(){
                location.replace("login.html");
            };
            div=document.querySelector(".container>div");
            div.appendChild(back);



            return;
        }

        chessBoard[row][col] = 1;

        me = !me;
        setScreenText(me);

    }



};